import { _decorator, Button, Component, EventTouch, Label, log, Node, Sprite, SpriteFrame, Tween, tween, v3, Vec3 } from 'cc';
import { GameUtil } from './GameUtil';
import { UICarriage } from './GameUI/UICarriage';
import { GameManager } from './GameManager';
import { EventManager, MyEvent } from '../AshFramework/Managers/EventManager';
import { BundleManager, Bundles } from '../AshFramework/Managers/BundleManager';
import { UIButton } from './GameUI/UIButton';
import { Money } from './Money';
import { addEnergy, addHp, energyPrice, EPOCH, epoch, EPOCHRANGE, evolutionPrice, TASKTYPE } from '../AshFramework/Datas/GameConstant';
import { ZTool } from '../AshFramework/Utils/ZTool';
import { MenuManager } from './MenuManager';
const { ccclass, property } = _decorator;

const carriagePos: Vec3[] = [v3(0, 185), v3(0, 440), v3(0, 695)]
const minY = 1355;//车厢移动的最小Y坐标
const maxY = 1865;//车厢移动的最大Y坐标

@ccclass('UpgradeController')
export class UpgradeController extends Component {
    @property(SpriteFrame)
    NormalSF: SpriteFrame = null;

    @property(SpriteFrame)
    ClickSF: SpriteFrame = null;

    @property(Node)
    UpgradePanel: Node = null;

    @property(Node)
    EvolutionPanel: Node = null;

    @property(Sprite)
    UpgradeSprite: Sprite = null;

    @property(Sprite)
    EvolutionSprite: Sprite = null;

    @property({ type: [Node] })
    ArrCarriage: Node[] = [];

    @property(Node)
    Carriage1Node: Node = null;

    @property(Node)
    Carriage2Node: Node = null;

    @property(Node)
    Carriage3Node: Node = null;

    @property(Node)
    EnergyNode: Node = null

    @property(Node)
    HPNode: Node = null

    @property(Node)
    UpNode: Node = null;

    @property(Node)
    DownNode: Node = null;

    @property(Node)
    EvolutionNode: Node = null;

    @property(Sprite)
    EvolutionRange: Sprite = null;

    @property(Label)
    EvolutionPrice: Label = null;

    private _targetPanel: Node = null;

    private _targetSprite: Sprite = null;
    private _arrCarriage: Node[] = [null, null, null];
    private _targetCarriage: Node = null;
    private _targetIndex: number = -1;

    private _evolutionPrice: number = 0;

    protected onLoad(): void {
        this._targetPanel = this.UpgradePanel;
        this._targetPanel.active = true;
    }


    protected start(): void {
        this.showUICarriages();
        this._targetCarriage = this._arrCarriage[0];
        this._targetIndex = 0;
        this.showCheckedCarriage();
        EventManager.Scene.emit(MyEvent.BUTTON_STYLE);
        this.updateEnergyBtn(true);
        this.updateHpBtn(true);
        EventManager.Scene.emit(MyEvent.ENERGY);
        EventManager.Scene.emit(MyEvent.HP);
        EventManager.Scene.emit(MyEvent.BUTTON_STYLE);
    }

    upgradeBtn(event: EventTouch) {
        if (this._targetPanel) {
            this._targetPanel.active = false;
        }
        this._targetPanel = this.UpgradePanel;
        this._targetPanel.active = true;

        this._targetSprite.spriteFrame = this.NormalSF;
        this._targetSprite = this.UpgradeSprite;
        this._targetSprite.spriteFrame = this.ClickSF;

    }

    evolutionBtn(event: EventTouch) {
        if (this._targetPanel) {
            this._targetPanel.active = false;
        }
        this._targetPanel = this.EvolutionPanel;
        this._targetPanel.active = true;

        this.showEvolutionPanel();

        this._targetSprite.spriteFrame = this.NormalSF;
        this._targetSprite = this.EvolutionSprite;
        this._targetSprite.spriteFrame = this.ClickSF;
    }

    //#region 升级界面
    energyBtn(event: EventTouch) {
        if (!event.target.getComponent(UIButton).isClick) {
            console.error("余额不足");
            GameUtil.showHint("余额不足");
            return;
        }
        GameManager.Instance.userData.energy += addEnergy;
        EventManager.Scene.emit(MyEvent.ENERGY);
        this.updateEnergyBtn();
    }

    hpBtn(event: EventTouch) {
        if (!event.target.getComponent(UIButton).isClick) {
            console.error("余额不足");
            GameUtil.showHint("余额不足");
            return;
        }
        GameManager.Instance.userData.hp += addHp[GameManager.Instance.userData.epoch];
        EventManager.Scene.emit(MyEvent.HP);
        this.updateHpBtn();
    }


    upBtn(event: EventTouch) {
        if (!this._targetCarriage) {
            console.error("找不到目标！！");
            return;
        }
        if (this._targetIndex == 2) {
            return;
        }

        for (let i = this._targetIndex + 1; i < 3; i++) {
            if (this._arrCarriage[i]) {
                this.swapCarriageByIndex(i);
                return;
            }
        }

    }
    downBtn(event: EventTouch) {
        if (!this._targetCarriage) {
            console.error("找不到目标！！");
            return;
        }
        if (this._targetIndex == 0) {
            return;
        }

        for (let i = this._targetIndex - 1; i >= 0; i--) {
            if (this._arrCarriage[i]) {
                this.swapCarriageByIndex(i);
                return;
            }
        }
    }

    updateEnergyBtn(isFirst: boolean = false) {
        if (isFirst) {
            this.EnergyNode.getComponent(Money).setMoney(GameManager.Instance.userData.curEnergyPrice);
            return;
        }

        let risePrice: number = GameManager.Instance.userData.curEnergyPrice;
        let riseNum = ZTool.GetRandomInt(risePrice * 0.01, risePrice * 0.2) + 1;
        GameManager.Instance.userData.curEnergyPrice += riseNum;
        GameManager.Instance.userData.gold -= risePrice;
        MenuManager.Instance.updateGold();
        this.EnergyNode.getComponent(Money).addMoney(riseNum);
        EventManager.Scene.emit(MyEvent.BUTTON_STYLE);
        //任务
        if (GameManager.Instance.userData.task.type === TASKTYPE.CONSUME) {
            GameManager.Instance.userData.task.curProgress += risePrice;
        }
    }

    updateHpBtn(isFirst: boolean = false) {
        if (isFirst) {
            this.HPNode.getComponent(Money).setMoney(GameManager.Instance.userData.curHpPrice);
            return;
        }

        let risePrice: number = GameManager.Instance.userData.curHpPrice;
        let riseNum = ZTool.GetRandomInt(risePrice * 0.01, risePrice * 0.2) + 1;
        GameManager.Instance.userData.curHpPrice += riseNum;
        GameManager.Instance.userData.gold -= risePrice;
        MenuManager.Instance.updateGold();
        this.HPNode.getComponent(Money).addMoney(riseNum);
        EventManager.Scene.emit(MyEvent.BUTTON_STYLE);
        //任务
        if (GameManager.Instance.userData.task.type === TASKTYPE.CONSUME) {
            GameManager.Instance.userData.task.curProgress += risePrice;
        }
    }

    showUICarriages() {
        let carriageCount = 0;
        let arrWeapon = GameManager.Instance.userData.weapon;
        for (let i = 0; i < 3; i++) {
            let carriageNode: Node = null;
            if (arrWeapon[i] != 0) {
                carriageCount++;
                carriageNode = this.ArrCarriage[arrWeapon[i] - 1];
                carriageNode.getComponent(UICarriage).unlock();
                carriageNode.position = carriagePos[i];
            }
            this._arrCarriage[i] = carriageNode;
        }
        // this.Carriage1Node.getComponent(UICarriage)
        if (carriageCount > 1) {
            this.setUICarriageMoveActive(true);
        } else {
            this.setUICarriageMoveActive(false);
        }
    }

    swapCarriage() {
        if (!this._targetCarriage || this._targetIndex == -1) return;
        let targetPos = carriagePos[this._targetIndex].clone();
        let swapIndx: number = -1;
        if (this._arrCarriage[0] && this._targetCarriage.position.y <= (carriagePos[0].y + carriagePos[1].y) / 2 && this._targetIndex != 0) {
            swapIndx = 0;
        } else if (this._arrCarriage[1] && this._targetCarriage.position.y <= (carriagePos[1].y + carriagePos[2].y) / 2 && this._targetCarriage.position.y > (carriagePos[0].y + carriagePos[1].y) / 2 && this._targetIndex != 1) {
            swapIndx = 1;
        } else if (this._arrCarriage[2] && this._targetCarriage.position.y > (carriagePos[1].y + carriagePos[2].y) / 2 && this._targetIndex != 2) {
            swapIndx = 2;
        }

        if (swapIndx == -1) return;

        let tempNode: Node = this._arrCarriage[swapIndx];
        this._arrCarriage[swapIndx] = this._arrCarriage[this._targetIndex];
        this._arrCarriage[this._targetIndex] = tempNode;
        this._targetIndex = swapIndx;
        this.updateUserWeapon();
        Tween.stopAllByTarget(tempNode);
        tween(tempNode)
            .to(0.2, { position: targetPos }, { easing: 'linear' })
            .start();
    }

    swapCarriageByIndex(index: number) {
        let tempNode: Node = this._arrCarriage[index];
        this._arrCarriage[index] = this._targetCarriage;
        this._arrCarriage[this._targetIndex] = tempNode;
        this.updateUserWeapon();
        Tween.stopAllByTarget(tempNode);
        tween(tempNode)
            .to(0.3, { position: carriagePos[this._targetIndex] }, { easing: `linear` })
            .start();
        Tween.stopAllByTarget(this._targetCarriage);
        tween(this._targetCarriage)
            .to(0.3, { position: carriagePos[index] }, { easing: 'linear' })
            .start();
        this._targetIndex = index;
    }

    setUICarriageMoveActive(bool: boolean) {
        this.UpNode.active = bool;
        this.DownNode.active = bool;
    }

    updateUserWeapon() {
        for (let i = 0; i < 3; i++) {
            let type: number = 0;
            if (this._arrCarriage[i]) {
                type = this._arrCarriage[i].getComponent(UICarriage).type;
            }
            GameManager.Instance.userData.weapon[i] = type;
        }
    }

    checkCarriage(carriage: Node): number {
        return this._arrCarriage.findIndex(e => e === carriage);
    }

    TouchStart(event: EventTouch) {
        this._targetIndex = this.checkCarriage(event.getCurrentTarget());
        if (this._targetIndex != -1) {
            this._targetCarriage = event.getCurrentTarget();
            this._targetCarriage.setSiblingIndex(99);
            this.showCheckedCarriage();
        }
    }

    TouchMove(event: EventTouch) {
        if (!this._targetCarriage) return;
        let newY = GameUtil.getBetween(event.getUILocation().y, minY, maxY);
        this._targetCarriage.worldPosition = v3(this._targetCarriage.worldPosition.x, newY);
        this.swapCarriage();
    }


    TouchEnd(event: EventTouch) {
        this._targetCarriage.position = carriagePos[this._targetIndex];
    }

    showCheckedCarriage() {
        if (!this._targetCarriage) return;
        for (let i = 0; i < 3; i++) {
            if (this._arrCarriage[i]) {
                this._arrCarriage[i].getComponent(UICarriage).checkedNode.active = false;
            }
        }
        this._targetCarriage.getComponent(UICarriage).checkedNode.active = true;
    }

    //#region 进化界面
    evolution() {
        if (GameManager.Instance.userData.gold < this._evolutionPrice) {
            // console.error("金币不足 无法进化！");
            GameUtil.showHint("金币不够");
            return;
        }

        let index = epoch.findIndex(e => e === GameManager.Instance.userData.curEpochProgress);
        if (index == -1 || index == epoch.length - 1) {
            console.error(`error:找到的时代坐标为${index}`);
        }
        //进化成功
        GameManager.Instance.userData.curEpochProgress = epoch[index + 1];
        GameManager.Instance.userData.epoch = EPOCH[epoch[index + 1]];
        //任务
        if (GameManager.Instance.userData.task.type === TASKTYPE.CONSUME) {
            GameManager.Instance.userData.task.curProgress += this._evolutionPrice;
        }
        //更新UI
        this.showEvolutionPanel();
        GameManager.Instance.saveData();
    }

    showEvolutionPanel() {
        //设置进度
        this.EvolutionRange.fillRange = EPOCHRANGE[GameManager.Instance.userData.curEpochProgress];
        //设置购买金额
        let index = epoch.findIndex(e => e === GameManager.Instance.userData.curEpochProgress);
        if (index == -1 || index == evolutionPrice.length) {
            console.error(`error:找到的时代坐标为${index}`);
        }
        this._evolutionPrice = evolutionPrice[index];
        // this.EvolutionPrice.string = GameUtil.formatNumber(this._evolutionPrice);
        this.EvolutionPrice.node.parent.getComponent(Money).setMoney(this._evolutionPrice);
        EventManager.Scene.emit(MyEvent.BUTTON_STYLE);
    }


    _updateEnergyBtn(isFirst: boolean = false) {
        if (isFirst) {
            this.EnergyNode.getComponent(Money).setMoney(GameManager.Instance.userData.curEnergyPrice);
            return;
        }

        let risePrice: number = GameManager.Instance.userData.curEnergyPrice;
        let riseNum = ZTool.GetRandomInt(risePrice * 0.01, risePrice * 0.2) + 1;
        GameManager.Instance.userData.curEnergyPrice += riseNum;
        GameManager.Instance.userData.gold -= risePrice;
        MenuManager.Instance.updateGold();
        this.EnergyNode.getComponent(Money).addMoney(riseNum);
        EventManager.Scene.emit(MyEvent.BUTTON_STYLE);
    }

    protected onEnable(): void {
        this._targetSprite = this.UpgradeSprite;
        this._targetSprite.spriteFrame = this.ClickSF;
        // this.showEvolutionPanel();

        this.Carriage1Node.on(Node.EventType.TOUCH_START, this.TouchStart, this);
        this.Carriage1Node.on(Node.EventType.TOUCH_MOVE, this.TouchMove, this);
        this.Carriage1Node.on(Node.EventType.TOUCH_END, this.TouchEnd, this);
        this.Carriage1Node.on(Node.EventType.TOUCH_CANCEL, this.TouchEnd, this);

        this.Carriage2Node.on(Node.EventType.TOUCH_START, this.TouchStart, this);
        this.Carriage2Node.on(Node.EventType.TOUCH_MOVE, this.TouchMove, this);
        this.Carriage2Node.on(Node.EventType.TOUCH_END, this.TouchEnd, this);
        this.Carriage2Node.on(Node.EventType.TOUCH_CANCEL, this.TouchEnd, this);

        this.Carriage3Node.on(Node.EventType.TOUCH_START, this.TouchStart, this);
        this.Carriage3Node.on(Node.EventType.TOUCH_MOVE, this.TouchMove, this);
        this.Carriage3Node.on(Node.EventType.TOUCH_END, this.TouchEnd, this);
        this.Carriage3Node.on(Node.EventType.TOUCH_CANCEL, this.TouchEnd, this);
        EventManager.on(MyEvent.CARRIAGE_BUY, this.showUICarriages, this);
    }

    protected onDisable(): void {
        this.Carriage1Node.off(Node.EventType.TOUCH_START, this.TouchStart, this);
        this.Carriage1Node.off(Node.EventType.TOUCH_MOVE, this.TouchMove, this);
        this.Carriage1Node.off(Node.EventType.TOUCH_END, this.TouchEnd, this);
        this.Carriage1Node.off(Node.EventType.TOUCH_CANCEL, this.TouchEnd, this);

        this.Carriage2Node.off(Node.EventType.TOUCH_START, this.TouchStart, this);
        this.Carriage2Node.off(Node.EventType.TOUCH_MOVE, this.TouchMove, this);
        this.Carriage2Node.off(Node.EventType.TOUCH_END, this.TouchEnd, this);
        this.Carriage2Node.off(Node.EventType.TOUCH_CANCEL, this.TouchEnd, this);

        this.Carriage3Node.off(Node.EventType.TOUCH_START, this.TouchStart, this);
        this.Carriage3Node.off(Node.EventType.TOUCH_MOVE, this.TouchMove, this);
        this.Carriage3Node.off(Node.EventType.TOUCH_END, this.TouchEnd, this);
        this.Carriage3Node.off(Node.EventType.TOUCH_CANCEL, this.TouchEnd, this);
        EventManager.off(MyEvent.CARRIAGE_BUY, this.showUICarriages, this);
    }


}


